﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Logging;
using WuDada.Core.Post;
using WuDada.Core.Post.Domain;
using WuDada.Core.Post.Service;
using WuDada.Core.SystemApplications.Domain;
using WuDada.Core.Member.Domain;
using WuDada.Core.Member;
using WuDada.Core.Member.Service;

public partial class admin_UC08_0811 : System.Web.UI.Page
{
    private ILog m_Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private PostFactory m_PostFactory;
    private IPostService m_PostService;
    private WebLogService m_WebLogService;
    private MemberFactory m_MemberFactory;
    private IMemberService m_MemberService;

    //熱門案件 NodeId=8
    private int m_NodeId = 8;

    private int m_Mode
    {
        get { if (ViewState["mode"] == null) { ViewState["mode"] = 0; } return int.Parse(ViewState["mode"].ToString()); }
        set { ViewState["mode"] = value; }
    }
    private string m_PicFileName
    {
        get { if (ViewState["picfilename"] == null) { ViewState["picfilename"] = string.Empty; } return ViewState["picfilename"].ToString(); }
        set { ViewState["picfilename"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        m_WebLogService = new WebLogService();
        m_PostFactory = new PostFactory();
        m_PostService = m_PostFactory.GetPostService();
        m_MemberFactory = new MemberFactory();
        m_MemberService = m_MemberFactory.GetMemberService();

        if (!IsPostBack)
        {
            pnlContent.Visible = false;
            SearchData();
            ShowMode();

        }
    }

    private void ShowMode()
    {
        if (m_Mode == 0)
        {
            btnAdd.Visible = true;
            btnSave.Visible = false;
            ddlType.Enabled = true;
        }
        else
        {
            btnAdd.Visible = false;
            btnSave.Visible = true;
            ddlType.Enabled = false;
        }
        RefreshDDLParent();
    }

    private void RefreshDDLParent()
    {
        IDictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("NodeId", m_NodeId.ToString());
        conditions.Add("Type", "1");

        IList<PostVO> parentList = m_PostService.GetPostList(conditions);
        ddlParent.Items.Clear();
        ddlParent.Items.Add(new ListItem("請選擇", string.Empty));
        if (parentList != null && parentList.Count > 0)
        {
            foreach (PostVO parent in parentList)
            {
                ddlParent.Items.Add(new ListItem(parent.Title, parent.PostId.ToString()));
            }
        }
    }

    private void SearchData()
    {
        //搜尋條件
        IDictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("NodeId", m_NodeId.ToString());
        conditions.Add("Title", txtSearchTitle.Text.Trim());

        //分頁
        AspNetPager1.RecordCount = m_PostService.GetPostCount(conditions);
        int pageIndex = (AspNetPager1.CurrentPageIndex - 1);
        int pageSize = AspNetPager1.PageSize;

        gvList.DataSource = m_PostService.GetPostList(conditions);
        gvList.DataBind();
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        SearchData();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        PostVO postVO = new PostVO();
        UIHelper.FillVO(pnlContent, postVO);
        if ("0".Equals(ddlType.SelectedValue) && !string.IsNullOrEmpty(ddlParent.SelectedValue))
        {
            postVO.ParentPost = m_PostService.GetPostById(int.Parse(ddlParent.SelectedValue));
        }
        postVO.Node = m_PostService.GetNodeById(m_NodeId);
        postVO.PicFileName = m_PicFileName;
        m_PostService.CreatePost(postVO);
        m_WebLogService.AddSystemLog(MsgVO.Action.新增, postVO);
        ClearUI();
        SearchData();
    }

    private void ClearUI()
    {
        m_Mode = 0;
        UIHelper.ClearUI(pnlContent);
        pnlContent.Visible = false;
        btnShowAdd.Enabled = true;
        ddlType.SelectedValue = string.Empty;
        ltlImg.Text = string.Empty;
    }

    private string GetPic(string fileName)
    {
        return "<img src='../../upload/" + fileName + "' width='145' height='108' border='0'>";
    }

    protected void gvList_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        string cmdName = e.CommandName;
        int postId = int.Parse(e.CommandArgument.ToString());
        PostVO postVO = m_PostService.GetPostByIdNoLazy(postId);
        switch (cmdName)
        {
            case "myModify":
                ClearUI();
                UIHelper.FillUI(pnlContent, postVO);
                m_Mode = postId;
                m_PicFileName = postVO.PicFileName;
                ltlImg.Text = GetPic(m_PicFileName);
                ShowMode();
                if (postVO.ParentPost != null)
                {
                    ddlParent.SelectedValue = postVO.ParentPost.PostId.ToString();
                }
                if (!string.IsNullOrEmpty(postVO.Winner))
                {
                    MemberVO memberVO = m_MemberService.GetMemberById(int.Parse(postVO.Winner));
                    if (memberVO != null)
                    {
                        lblWinner.Text = memberVO.Name;
                    }
                }
                if (!string.IsNullOrEmpty(postVO.CreateMember))
                {
                    MemberVO memberVO = m_MemberService.GetMemberById(int.Parse(postVO.CreateMember));
                    if (memberVO != null)
                    {
                        lblCreateMember.Text = memberVO.Name;
                    }
                }
                pnlContent.Visible = true;
                break;
            case "myDel":
                if (m_PostService.GetPostCount(new Dictionary<string, string>() { { "ParentPostId", postVO.PostId.ToString() } }) > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("此為案件主體，底下上有其他項目，無法刪除。"), false);
                }
                else
                {
                    m_PostService.DeletePost(postVO);
                    m_WebLogService.AddSystemLog(MsgVO.Action.刪除, postVO);
                }
                break;

            default:
                break;
        }
        SearchData();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearUI();
        ShowMode();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            PostVO postVO = m_PostService.GetPostById(m_Mode);
            UIHelper.FillVO(pnlContent, postVO);
            postVO.PicFileName = m_PicFileName;
            if ("0".Equals(ddlType.SelectedValue) && !string.IsNullOrEmpty(ddlParent.SelectedValue))
            {
                postVO.ParentPost = m_PostService.GetPostById(int.Parse(ddlParent.SelectedValue));
            }
            else
            {
                postVO.ParentPost = null;
            }
            m_PostService.UpdatePost(postVO);
            m_WebLogService.AddSystemLog(MsgVO.Action.修改, postVO);
            SearchData();
            ClearUI();
            ShowMode();
        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
            lblMsg.Text = ex.ToString();
        }
    }

    protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gv = (GridView)sender;
        if (e.Row.RowIndex != -1)
        {
            Control ctrl = e.Row;
            int postId = int.Parse(UIHelper.FindHiddenValue(ref ctrl, "hdnPostId"));
            PostVO postVO = m_PostService.GetPostByIdNoLazy(postId);
            if (postVO.ParentPost != null)
            {
                UIHelper.SetLabelText(ref ctrl, "lblCaseName", postVO.ParentPost.Title);
            }
        }
    }

    protected void btnShowAdd_Click(object sender, EventArgs e)
    {
        ClearUI();
        m_PicFileName = string.Empty;
        ShowMode();
        pnlContent.Visible = true;
        btnShowAdd.Enabled = false;
    }

    protected void ddlSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        SearchData();
    }

    protected void btnUpliad_Click(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetFileName(hpf.FileName);
                    hpf.SaveAs(Server.MapPath("~\\") + "\\upload\\" + fileName);
                    ltlImg.Text = GetPic(fileName);
                    m_PicFileName = fileName;
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("請點選您要上傳的照片!"), false);
                    return;
                }
            }
        }
        catch
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("檔案傳輸錯誤!"), false);
            return;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        SearchData();
    }

    protected void btnGetLatLgn_Click(object sender, EventArgs e)
    {
        PostVO post = new PostVO();
        post.City = txtCity.Text.Trim();
        post.Area = txtArea.Text.Trim();
        post.Road = txtRoad.Text.Trim();        
        GetMap(post);
        txtLat.Text = post.Lat;
        txtLng.Text = post.Lng;
    }

    private static void GetMap(PostVO post)
    {
        if (!string.IsNullOrEmpty(post.Address))
        {
            IList<string> latLng = GoogleApiHelper.GetLatLng(post.Address);
            if (latLng != null && latLng.Count == 2)
            {
                post.Lat = latLng[0].Substring(0, 10);
                post.Lng = latLng[1].Substring(0, 10);
            }
        }
    }
}